<template>
  <div class="contaner">
    <el-drawer title="配置参数" v-model="csOpen" size="40%" :show-close="false">
      <el-form ref="genForm" class="gen-form" :model="clientParam" size="small" label-width="150px">
        <el-row :gutter="10">
          <el-col :span="12">
            <el-form-item label="选择数据源" prop="datasourceConfigId"
                          :rules="{required: true, message: '请选择数据源'}">
              <FmSelectTable @submitdata="onDataSourceChange" check-type="single"
                             v-model:value="clientParam.datasourceConfigId"
                             title="数据源选择" :columns="selectcolumns" keys="id" lable="dbName"
                             url="/process/generator" tableName="datasourceconfig">
              </FmSelectTable>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item v-show="showTable" label="包名（package）" :rules="{required: true, message: '请选择包名'}">
              <el-input v-model="clientParam.packageName" placeholder="可选，如：cn.studyjava.xxx"
                        maxlength="100"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item v-show="showTable" label="模块名称" :rules="{required: true, message: '请填写模块名称'}">
              <el-input v-model="clientParam.module"
                        maxlength="100"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item v-show="showTable" label="删除前缀">
              <el-input v-model="clientParam.delPrefix" placeholder="可选，如：sys_user对应Java类为User(多前缀逗号隔开)"
                        maxlength="100"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item v-show="showTable" label="作者名">
              <el-input v-model="clientParam.author" placeholder="可选，如：author" maxlength="100"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item v-show="showTable" label="选择模板" :rules="{required: true, message: '请选择模板'}">
              <FmSelectTable check-type="single" v-model:value="clientParam.groupId"
                             title="选择模板" :columns="selectcolumns1" keys="id" lable="groupName"
                             url="/process/generator" tableName="templategroup">
              </FmSelectTable>
            </el-form-item>
          </el-col>
          <el-form-item>
            <el-button  icon="VideoPlay" v-show="showTable" type="primary" @click="onGenerate(genForm)">
              生成代码
            </el-button>
          </el-form-item>
        </el-row>
      </el-form>
    </el-drawer>
    <el-row  :gutter="10">
      <el-col :span="24">
        <el-scrollbar>
          <el-form :model="pageDto" ref="queryForm" :inline="true" v-show="showSearch"  label-width="68px">
            <el-form-item  label="表名"  prop="tableName">
              <el-input  v-model="pageDto['tableName']" clearable
                          @keyup.enter.native="handleQuery"></el-input>
            </el-form-item>
            <el-form-item  label="表注释"  prop="comment">
              <el-input  v-model="pageDto['comment']" clearable
                         @keyup.enter.native="handleQuery"></el-input>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="search" @click="handleQuery">搜索</el-button>
              <el-button icon="RefreshRight" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
          <el-row :gutter="10" style="margin-bottom: 8px;">
            <el-col :span="1.5" >
              <el-button  icon="Setting" type="primary" @click="csOpen=true">配置参数</el-button>
            </el-col>
            <right-toolbar v-model:showSearch="showSearch" @queryTable="handleQuery"
                           ></right-toolbar>
          </el-row>

          <el-table :data="tableListData" @selection-change="handleSelectionChange" class="table"
                    header-cell-class-name="table-header">
            <el-table-column type="selection" width="55" align="center"></el-table-column>
            <el-table-column label="表名" property="tableName" align="center">
            </el-table-column>
            <el-table-column label="备注" property="comment" align="center">
            </el-table-column>
            <el-table-column label="操作" align="center">
              <template v-slot="scope">
                <el-button type="primary" link icon="Setting" @click="opencolumnlist(scope.row.tableName)">编辑
                </el-button>
              </template>
            </el-table-column>
          </el-table>
          <div class="pagination">
            <el-pagination
                background
                :page-sizes="[4, 7, 9, 10]"
                layout="total, sizes, prev, pager, next, jumper"
                :current-page="pageDto.page"
                :page-size="pageDto.size"
                :total="pageTotal"
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
            ></el-pagination>
          </div>
        </el-scrollbar>
      </el-col>
    </el-row>
    <el-drawer title="列属性" v-model="columnOpen" size="50%">
      <el-table :data="columnlist" class="table">
        <el-table-column type="selection" width="55" align="center"></el-table-column>
        <el-table-column label="列名" property="columnName" align="center">
        </el-table-column>
        <el-table-column label="备注" property="comment" align="center">
        </el-table-column>
        <el-table-column label="操作" align="center">
          <template v-slot="scope">
            <el-button type="primary" link icon="Setting" @click="openValueProcess(scope.row)">值规则</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-drawer>
    <el-drawer title="值规则设计" destroy-on-close v-model="valueRuleOpen" size="100%" style="padding: 0px"
               :with-header="false">
      <template #default style="padding: 0px;height: 100%;">
        <el-icon style="    top: 5px;cursor: pointer ;
    right: 10px;
    z-index: 1000;position: absolute" @click="closeValueRule">
          <Close/>
        </el-icon>
        <ValueRuleProcess :value="valueRule['content']" :columns="columnlist"
                          @saveData="saveValueRule"></ValueRuleProcess>
      </template>
    </el-drawer>

    <el-dialog
        :title="datasourceTitle"
        v-model="datasourceDlgShow"
        :close-on-press-escape="false"
        :close-on-click-modal="false"
    >
      <el-form
          ref="datasourceForm"
          :model="datasourceFormData"
          :rules="datasourceRule"
          size="small"
          label-width="120px"
      >
        <el-form-item label="数据库分组" prop="dbGroupName">
          <el-input v-model="datasourceFormData.dbGroupName" placeholder="数据库分组名称(名称自定义，可重复)"
                    maxlength="64"/>
        </el-form-item>
        <el-form-item label="数据库类型">
          <el-select
              v-model="datasourceFormData.dbType"
              filterable
              default-first-option
          >
            <el-option
                v-for="item in dbTypeConfig"
                :key="item.dbType"
                :label="item.label"
                :value="item.dbType"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="数据库描述" prop="dbDesc">
          <el-input v-model="datasourceFormData.dbDesc" placeholder="数据库描述" maxlength="64"/>
        </el-form-item>
        <el-form-item label="Host" prop="host">
          <el-input v-model="datasourceFormData.host" placeholder="地址" maxlength="100"/>
        </el-form-item>
        <el-form-item label="Port" prop="port">
          <el-input v-model="datasourceFormData.port" placeholder="端口" maxlength="10"/>
        </el-form-item>
        <el-form-item :label="dbNamePlaceholder" prop="dbName">
          <el-input v-model="datasourceFormData.dbName" :placeholder="dbNamePlaceholder"
                    maxlength="64"/>
        </el-form-item>
        <el-form-item label="连接类型" v-show="showOracleFields">
          <el-select v-model="datasourceFormData.oracleConnType">
            <el-option
                v-for="item in oracleConnTypeList"
                :key="item.val"
                :label="item.lab"
                :value="item.val"
            />
          </el-select>
        </el-form-item>
        <el-form-item v-show="showPgSqlSchema" :label="schemaPlaceholder" :prop="schemaPlaceholder">
          <el-input v-model="datasourceFormData.schemaName" :placeholder="schemaPlaceholder+',如SCOTT'"
                    maxlength="64"/>
        </el-form-item>
        <el-form-item label="Username" prop="username">
          <el-input v-model="datasourceFormData.username" placeholder="用户名" maxlength="100"/>
        </el-form-item>
        <el-form-item label="角色" v-show="showOracleFields">
          <el-select v-model="datasourceFormData.oracleRole" clearable>
            <el-option
                v-for="item in oracleRoleList"
                :key="item.val"
                :label="item.lab"
                :value="item.val"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="Password" prop="password">
          <el-input v-model="datasourceFormData.password" type="password" placeholder="密码"
                    maxlength="100"/>
        </el-form-item>
        <el-form-item label="包名" prop="packageName">
          <el-input v-model="datasourceFormData.packageName" placeholder="包名（package）"
                    maxlength="100"/>
        </el-form-item>
        <el-form-item label="删除前缀" prop="delPrefix">
          <el-input v-model="datasourceFormData.delPrefix"
                    placeholder="删除前缀（表名sys_user删除前缀sys_对应bean为User）多前缀逗号隔开"
                    maxlength="200"/>
        </el-form-item>
        <el-form-item label="作者名" prop="author">
          <el-input v-model="datasourceFormData.author" placeholder="作者名" maxlength="100"/>
        </el-form-item>
        <el-form-item label="代码生成器模板" prop="delPrefix">
          <el-select
              v-model="datasourceFormData.groupId"
              placeholder="选择模板所在组"
              size="small"
              style="margin-bottom: 10px; width: 100%;"
          >
            <el-option
                v-for="item in groupData"
                :key="item.id"
                :label="item.groupName"
                :value="item.id"
            >
              {{ item.groupName }}
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="success" @click="onDatasourceTest(datasourceForm)">测试连接</el-button>
          <el-button type="primary" @click="onDatasourceSave(datasourceForm)">保存</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

    <!-- 预览界面 -->
    <el-dialog :title="preview.title" v-model="preview.open" width="80%" top="5vh" append-to-body destroy-on-close>
      <el-tabs v-model="preview.activeName" style="height: 100%;">
        <el-tab-pane
            v-for="(value, key) in preview.data"
            :label="value.fileName"
            :name="value.fileName"
            :key="value.fileName"
            style="height: 400px;"
        >
          <el-scrollbar style="height:400px" view-style="height:100%">
            <el-link :underline="false" icon="DocumentCopy" @click="copyText(value.content)" style="float:right">复制
            </el-link>
            <pre v-highlight><code style="display: contents;" class="java">{{ value.content }}</code></pre>
          </el-scrollbar>
        </el-tab-pane>
      </el-tabs>
      <template #footer>
        <el-button type="primary" icon="download" @click="downloadAll">下载</el-button>
      </template>
    </el-dialog>

  </div>
</template>
<script setup lang="ts">
import {fetchData, delData, saveorUpadateDate, deteleAllData} from '@/api/index';

const current_datasource_id_key = "gen-datasource-id"
import {ref, reactive, onMounted, nextTick, computed, watch} from "vue"
import {ElMessage, ElMessageBox, ElTree, FormInstance} from "element-plus";
import {useRouter} from "vue-router";
import {saveAs} from 'file-saver'
import CreateRule from "@/components/ValueRule/index.vue"
import ValueRuleProcess from "@/components/ValueRuleProcess/index.vue"
import Tags from "@/components/common/Tags.vue";
import JSZip from "jszip";

const object = ref({
  rules: 'and',
  list: []
})
const DB_TYPE = {
  MySQL: 1,
  Oracle: 2,
  SQL_Server: 3,
  PostgreSQL: 4,
  Dm: 5
}
const pageDto = reactive({
  current: 1,
  size: 10
})
let pageTotal = ref(0)
const groupId = ref('')
const groupData = ref([])
const showTable = ref(false)
const drawer = ref(false)
const columnOpen = ref(false)
let genForm = ref(null)
let queryForm = ref<FormInstance>();
let showSearch=ref(true)
const clientParam = ref({
  datasourceConfigId: '',
  tableNames: [],
  templateConfigIdList: [],
  packageName: '',
  delPrefix: '',
  groupId: '',
  author: '',
  tableId: '',
})
const preview = ref({
  open: false,
  title: "代码预览",
  data: {},
  activeName: ""
})
const valueRuleOpen = ref(false)
const filterText = ref('')
const columnlist = ref([])
const treeRef = ref<InstanceType<typeof ElTree>>()
let csOpen = ref(false)
let valueRule = ref({})
const currentNode = ref({})
const tablecolumn = ref({})
const curcolumn = ref({})
const props = {
  label: 'tableName',
  children: 'children',
  isLeaf: 'leaf',
}
const selectcolumns = [
  {
    "label": "数据库编号",//标签名称
    "index": "id",//数据库索引
    "rules": [
      {required: true, message: "请输入主键", trigger: "blur",},
    ],//值规则
    "search": true,//是否是搜索表单
    "dataType": "text",//值值类型默认字符类型
    "addable": false
  },
  {
    "label": "类型",//标签名称
    "index": "dbType",//数据库索引
    "rules": [
      {max: 50, message: '接口编号长度最大为  50个字符', trigger: 'blur'},
    ],//值规则
    "search": true,//是否是搜索表单
    "dataType": "text",//值值类型默认字符类型
  },
  {
    "label": "名称",//标签名称
    "index": "dbName",//数据库索引
    "rules": [
      {max: 50, message: '接口编号长度最大为  50个字符', trigger: 'blur'},
    ],//值规则
    "search": true,//是否是搜索表单
    "dataType": "text",//值值类型默认字符类型
  },
  {
    "label": "主机",//标签名称
    "index": "host",//数据库索引
    "rules": [
      {max: 50, message: '接口编号长度最大为  50个字符', trigger: 'blur'},
    ],//值规则
    "search": true,//是否是搜索表单
    "dataType": "text",//值值类型默认字符类型
  },
  {
    "label": "端口",//标签名称
    "index": "port",//数据库索引
    "rules": [
      {max: 50, message: '接口编号长度最大为  50个字符', trigger: 'blur'},
    ],//值规则
    "dataType": "text",//值值类型默认字符类型
  },
]
let selectcolumns1 = [{
  "label": "分组编号",//标签名称
  "index": "id",//数据库索引
  "rules": [
    {required: true, message: "请输入主键", trigger: "blur",},
  ],//值规则
  "search": true,//是否是搜索表单
  "dataType": "text",//值值类型默认字符类型
  "addable": false
},
  {
    "label": "分组名称",//标签名称
    "index": "groupName",//数据库索引
    "rules": [
      {required: true, message: '不能为空', trigger: 'blur'}
    ],//值规则
    "search": true,//是否是搜索表单
    "dataType": "text",//值值类型默认字符类型
  }]
let tableSearch = ref('')
let datasourceGroupMap = ref({})
let datasourceConfigList = ref([])
let tableListData = ref([])
let templateListData = ref([])
let templateListSelect = ref([])
let datasourceTitle = ref('新建连接')
let datasourceDlgShow = ref(false)
let multipleSelection = ref({})
let datasourceFormData = ref({
  id: 0,
  dbGroupName: '',
  dbType: 1,
  dbDesc: '',
  host: '',
  port: '',
  username: '',
  password: '',
  dbName: '',
  oracleConnType: '',
  oracleRole: '',
  schemaName: '',
  packageName: '',
  delPrefix: '',
  groupId: '',
  author: ''
})
let dbTypeConfig = ref([])
let oracleConnTypeList = ref([{
  lab: "服务名",
  val: 1
}, {
  lab: "SID",
  val: 2
}])
let oracleRoleList = ref([{
  lab: "default",
  val: ""
}, {
  lab: "SYSDBA",
  val: 1
}, {
  lab: "SYSOPER",
  val: 2
}])
let datasourceRule = {
  host: [
    {required: true, message: '不能为空', trigger: 'blur'}
  ],
  port: [
    {required: true, message: '不能为空', trigger: 'blur'}
  ],
  username: [
    {required: true, message: '不能为空', trigger: 'blur'}
  ],
  password: [
    {required: true, message: '不能为空', trigger: 'blur'}
  ],
  dbName: [
    {required: true, message: '不能为空', trigger: 'blur'}
  ]
}
let router = useRouter()
let datasourceForm = ref(null)
const filterNode = (value: string, data) => {
  if (!value) return true
  return data.tableName.includes(value)
}
const handleNodeClick = (e: any, node: any) => {
  if (!node.isLeaf) {
    clientParam.value.tableId = node["label"]
    clientParam.value.tableNames = [node["label"]]
  }
}
let handleSizeChange = (size: any) => {
  pageDto.size = size;
  loadTable(clientParam.value.datasourceConfigId)
}
let handleCurrentChange = (page: any) => {
  pageDto.current = page;
  loadTable(clientParam.value.datasourceConfigId)

}
const opencolumnlist = (table) => {
  loadcolumn(table);
  tablecolumn.value = table
  columnOpen.value = true
}
const copyText = (data) => {
  navigator.clipboard.writeText(data)
      .then(() => {
        ElMessage.success('复制成功')
      })
      .catch(() => {
        ElMessage.error('复制失败')
      })
}
const loadValueRule = (column) => {
  curcolumn.value = column
  fetchData(`/process/generator/valueRule/getcolumnvalueRule/${clientParam.value.datasourceConfigId}/${column}`).then(res => {
    valueRule.value = res
    debugger
    if (res != '' && res != undefined) {
      valueRule.value["content"] = (res.content == undefined) ? {} : JSON.parse(valueRule.value["content"])
    } else {
      valueRule.value = {
        content: {},
        tableName: tablecolumn.value,
        column: curcolumn.value,
        databsourceId: clientParam.value.datasourceConfigId
      }
    }
    valueRuleOpen.value = true
  })

}
const openValueProcess = (row) => {
  loadValueRule(row["columnName"])
}
const closeValueRule = () => {
  valueRuleOpen.value = false
  valueRule.value = {}
}
const buildTreeData = (rows) => {
  const treeData = []
  const codeMap = {}
  // 把列表数据转换到map中,key为模板名
  // value是个List
  for (let i = 0, len = rows.length; i < len; i++) {
    const row = rows[i]
    const folder = row.folder
    let list = codeMap[folder]
    if (!list) {
      list = []
      codeMap[folder] = list
    }
    list.push(row)
  }
  // 把这个map对象转成tree格式数据
  for (const folder in codeMap) {
    const codeFileArr = codeMap[folder]
    // 父节点
    const treeElement = {
      fileName: folder,
      children: buildChildren(codeFileArr)
    }

    treeData.push(treeElement)
  }
  return treeData
}
const buildChildren = (codeFileArr) => {
  const children = []
  for (let i = 0, len = codeFileArr.length; i < len; i++) {
    const codeFile = codeFileArr[i]
    const child = {
      fileName: codeFile.fileName,
      content: codeFile.content
    }
    children.push(child)
  }
  return children
}
const downloadAll = () => {
  let data = preview.value.data
  data = buildTreeData(data)
  const zip = new JSZip()
  data.forEach(row => {
    const children = row.children
    const isFolder = children.length > 0
    if (isFolder) {
      // 创建文件夹 将文件层级的点 改为 路径 斜杠
      let folderName = row.fileName.replaceAll('.', '/');
      const folderZip = zip.folder(folderName)
      children.forEach(child => {
        // 文件放入文件夹中
        folderZip.file(child.fileName, child.content)
      })
    }
  })
  // 下载
  zip.generateAsync({type: 'blob'}).then(function (content) {
    // see FileSaver.js
    saveAs(content, `code-${new Date().getTime()}.zip`)
  })
}

const saveValueRule = (data) => {
  let item = {
    id: valueRule.value.id,
    content: JSON.stringify(data),
    tableName: tablecolumn.value,
    column: curcolumn.value,
    databsourceId: clientParam.value.datasourceConfigId
  }
  saveorUpadateDate("/process/generator/valueRule/save", item).then(res => {
    ElMessage.success(res)
  })
}
const loadcolumn = (table) => {
  fetchData(`/process/generator/datasourceconfig/column/${clientParam.value.datasourceConfigId}/${table}`).then((res) => {
    columnlist.value = res
  })
}
const loadNode = async (node, resolve) => {
  if (node.level === 0) {
    // 顶层节点，直接加载
    let data = tableListData.value
    resolve(data)
  } else {
    fetchData(`/process/generator/datasourceconfig/column/${clientParam.value.datasourceConfigId}/${node.label}`).then((res) => {
      console.log(res)
      let data = [];
      for (let i = 0; i < res.length; i++) {
        let item = res[i]
        item["leaf"] = true
        item["tableName"] = item["columnName"]
        data.push(item)
      }

      resolve(data)
    })
  }
}
const fetchTableconlmn = async (table) => {
  fetchData(`/process/generator/datasourceconfig/column/${clientParam.value.datasourceConfigId}/${table}`).then((res) => {
    console.log(res)
    return res;
  })
}
let handleQuery = () => {
  pageDto.current = 1;
  loadTable(clientParam.value.datasourceConfigId)
}
/** 重置按钮操作 */
let resetForm = (formName: FormInstance | undefined) => {
  if (formName !== undefined) {
    formName.resetFields()
  }
}
/** 重置按钮操作 */
let resetQuery = () => {
  {
    resetForm(queryForm.value);
    handleQuery();
  }
}

let handleSelectionChange = (val: any) => {
  let tableNames = val.map(e => {
    return e["tableName"];
  })

  clientParam.value.tableId = tableNames
  clientParam.value.tableNames = tableNames
}

let showPgSqlSchema = computed(() => {
  return (datasourceFormData.value.dbType === DB_TYPE.PostgreSQL || datasourceFormData.value.dbType === DB_TYPE.Oracle)
})
let dbNamePlaceholder = computed(() => {
  if (datasourceFormData.value.dbType === DB_TYPE.Oracle) {
    return "服务名";
  } else {
    return "数据库";
  }
})
let schemaPlaceholder = computed(() => {
  if (datasourceFormData.value.dbType === DB_TYPE.Oracle) {
    return "数据库";
  } else {
    return "schema";
  }
})
let showOracleFields = computed(() => {
  return datasourceFormData.value.dbType === DB_TYPE.Oracle;
})
const loadDataSource = () => {
  const cacheId = getCurrentDataSourceId()
  saveorUpadateDate('/process/generator/datasourceconfig/list', {}).then((resp) => {
    let id
    const list = resp.records
    getDatasourceGroupMap(list)
    datasourceConfigList.value = list
    for (const item of list) {
      // 缓存id是否有效
      if (item.id === cacheId) {
        id = item.id
        break
      }
    }
    // if (!id && list.length > 0) {
    //   id = list[0].id
    // }
    // if (id) {
    //   onDataSourceChange({id: parseInt(id)})
    // }
  })
}
const getCurrentDataSourceId = () => {
  const id = localStorage.getItem(current_datasource_id_key)
  return parseInt(id) || ''
}
const loadTemplate = () => {
  saveorUpadateDate('/process/generator/templateconfig/list', {}).then(resp => {
    templateListData.value = resp.records
  })
}
const loadDbType = () => {
  saveorUpadateDate('/process/generator/datasourceconfig/dbtype', {}).then(resp => {
    dbTypeConfig.value = resp
  })
}
const loadGroups = () => {
  saveorUpadateDate(`/process/generator/templategroup/list/`, {}).then((resp) => {
    groupData.value = resp.records
  })
}
watch(filterText, (val) => {
  treeRef.value!.filter(val)
})

onMounted(() => {
  loadDataSource()
  loadTemplate()
  loadDbType()
  loadGroups()
})

const bindEvent = (eventCenter) => {
  eventCenter.on("node:click", (args) => {
    console.log("节点单击", args);
    drawer.value = true;
    currentNode.value = args;
  });
}
const tableRowClassName = ({row, index}) => {
  // console.log("tablerow="+row.tableName+","+index)
  row.hidden = false
  if (tableSearch.value.length === 0) {
    return ''
  }
  // console.log("tablerow="+row.tableName +","+ row.tableName.indexOf(this.tableName)+","+(!(row.tableName && row.tableName.indexOf(this.tableSearch) > -1)))
  if (!(row.tableName && row.tableName.toLowerCase().indexOf(tableSearch.value.toLowerCase()) > -1)) {
    row.hidden = true
    return 'hidden-row';
  }
  return ''
}
const templateTableRowClassName = ({row, index}) => {
  // console.log("temprow="+row.id+",rowGroupId="+row.groupId+", this.groupId="+ this.groupId)
  row.hidden = false
  if (groupId.value == '' || groupId.value <= 0) {
    return ''
  }
  // console.log("temprow="+row.groupId +","+(row.groupId && row.groupId == this.groupId))
  if (row.groupId && row.groupId == groupId.value) {
    return ''
  }
  row.hidden = true
  return 'hidden-row';
}
const getDatasourceLabel = (item: any) => {
  const schema = item.schemaName ? `/${item.schemaName}` : ''
  const dbDesc = item.dbDesc ? item.dbDesc + '   ' : ''
  return `${dbDesc}${item.dbName}${schema} (${item.host}) - ${item.username}`
}
const getDatasourceGroupMap = (list: any) => {
  const groups = {}
  for (const item of list) {
    let groupName = item.dbGroupName || '';
    groups[groupName] = groups[groupName] || []
    groups[groupName].push(item)
  }
  datasourceGroupMap.value = groups
}
const setCurrentDataSourceId = (id: any) => {
  localStorage.setItem(current_datasource_id_key, id)
}
const packageOracleFields = () => {
  // 处理oracle连接数据
  if (datasourceFormData.value.dbType === DB_TYPE.Oracle) {
    // 处理连接类型
    if (datasourceFormData.value.oracleConnType == 1) {
      datasourceFormData.value.dbName = "/" + datasourceFormData.value.dbName;
    } else if (datasourceFormData.value.oracleConnType == 2) {
      datasourceFormData.value.dbName = ":" + datasourceFormData.value.dbName;
    }
    // 处理账号角色
    if (datasourceFormData.value.oracleRole == 1) {
      datasourceFormData.value.username += " AS SYSDBA";
    } else if (datasourceFormData.value.oracleRole == 2) {
      datasourceFormData.value.username += " AS SYSOPER";
    }
  }
}
const unPackOracleFields = (item: any) => {
  // 处理oracle属性 拆包
  if (item.dbType === DB_TYPE.Oracle) {
    // 处理连接类型
    if (item.dbName.startsWith("/")) {
      item.oracleConnType = 1;
      item.dbName = item.dbName.replace("/", "");
    } else if (item.dbName.startsWith(":")) {
      item.oracleConnType = 2;
      item.dbName = item.dbName.replace(":", "");
    }
    // 处理账号角色
    if (item.username.includes("AS SYSDBA")) {
      item.oracleRole = 1;
      item.username = item.username.replace(" AS SYSDBA", "");
    } else if (item.username.includes("AS SYSOPER")) {
      item.oracleRole = 2;
      item.username = item.username.replace(" AS SYSOPER", "");
    }
  }
}
const onDataSourceAdd = () => {
  datasourceTitle.value = '新建连接'
  Object.keys(datasourceFormData.value).forEach(key => {
    datasourceFormData.value[key] = ''
  })
  datasourceFormData.value.id = 0
  datasourceFormData.value.dbType = 1
  datasourceDlgShow.value = true
  nextTick(() => {
    if (groupData.value.length > 0) {
      datasourceFormData.value.groupId = groupData[0].value.id
    }
  })
}
const onTemplateGroupChange = (templateId: any) => {
  //切换模板下拉框  清除先前被选中的模板
  templateListSelect.clearSelection();
}
const onTableListSelect = (selectedRows: any) => {
  clientParam.value.tableNames = selectedRows
      .filter(row => row.hidden === undefined || row.hidden === false)
      .map(row => row.tableName)
}
const onTemplateListSelect = (selectedRows: any) => {
  debugger
  clientParam.value.templateConfigIdList = selectedRows
      .filter(row => row.hidden === undefined || row.hidden === false)
      .map(row => row.id)
}
const onDataSourceChange = (datasourceConfig: any) => {
  let datasourceConfigId = datasourceConfig["id"]
  setCurrentDataSourceId(datasourceConfigId)
  clientParam.value.datasourceConfigId = datasourceConfigId
  loadTable(datasourceConfigId)
}
const loadTable = (datasourceConfigId) => {
  fetchData(`/process/generator/datasourceconfig/table/${datasourceConfigId}`, pageDto).then(resp => {
    showTable.value = true
    tableListData.value = resp.records
    pageTotal.value = resp.total
  })
}
const onDataSourceUpdate = (item: any) => {
  datasourceTitle.value = '修改连接'
  unPackOracleFields(item);
  Object.assign(datasourceFormData.value, item)
  datasourceDlgShow.value = true
}
const onDataSourceDuplicate = (item: any) => {
  datasourceTitle.value = `${item.host} Copy`
  Object.assign(datasourceFormData.value, item)
  datasourceFormData.value.id = 0
  datasourceDlgShow.value = true
}
const onDataSourceDelete = (row: any) => {
  ElMessageBox.confirm(`确认要删除 ${row.dbName} 吗？`, function (done) {
    const data = {
      id: row.id
    }
    saveorUpadateDate('/process/generator/datasourceconfig/del', data).then(() => {
      done()
      location.reload()
    })
  })
}
const onGenerate = (form, target: any = {}) => {
  form.validate((valid) => {
    if (valid) {
      if (clientParam.value.tableNames.length === 0) {
        ElMessage.success('请勾选表')
        return
      }
      // if (clientParam.value.templateConfigIdList.length === 0) {
      //   ElMessage.success('请勾选模板')
      //   return
      // }
      const config = JSON.stringify(clientParam.value)
      console.log(target);
      if (target === '_blank') {
        //新窗口打开
        // this.goRouteNewWindow(`result/${config}`)
      } else {
        // router.push({
        //   path: `result`, query: {
        //     config: config
        //   }
        // })
        saveorUpadateDate('/process/generator/generate/code', clientParam.value).then(resp => {

          preview.value.open = true
          preview.value.data = resp
          preview.value.activeName = resp[0].fileName
        })
      }
    }
  })
}
const onDatasourceTest = (form: any) => {
  packageOracleFields();
  form.validate((valid) => {
    if (valid) {
      saveorUpadateDate('/process/generator/datasourceconfig/test', datasourceFormData.value).then(resp => {
        if (datasourceFormData.value.dbType === DB_TYPE.Oracle) {
          // 处理连接类型
          if (datasourceFormData.value.oracleConnType == 1) {
            datasourceFormData.value.dbName = datasourceFormData.value.dbName.replace("/", "");
          } else if (datasourceFormData.value.oracleConnType == 2) {
            datasourceFormData.value.dbName = datasourceFormData.value.dbName.replace(":", "");
          }
          // 处理账号角色
          if (datasourceFormData.value.oracleRole == 1) {
            datasourceFormData.value.username = datasourceFormData.value.username.replace(" AS SYSDBA", "");
          } else {
            datasourceFormData.value.username = datasourceFormData.value.username.replace(" AS SYSOPER", "");
          }
        }
        ElMessage.success('连接成功')
      }, err => {
        unPackOracleFields(datasourceFormData.value);
      })
    }
  })
}

const onDatasourceSave = (form: any) => {
  packageOracleFields();
  form.validate((valid) => {
    if (valid) {
      saveorUpadateDate('/process/generator/datasourceconfig/test', datasourceFormData.value).then(resp => {
        if (datasourceFormData.value.id) {
          saveorUpadateDate('/process/generator/datasourceconfig/update', datasourceFormData.value).then(resp => {
            location.reload()
          })
        } else {
          saveorUpadateDate('/process/generator/datasourceconfig/add', datasourceFormData.value).then(resp => {
            ElMessage.success('添加成功')
            loadDataSource()
            datasourceDlgShow.value = false
          })
        }
      })
    }
  })
}
</script>
<style>
.table {
  width: 100%;
  font-size: 14px;
}
</style>

